# -*- coding: utf-8 -*-#
__author__ = 'yangq'
import os
from tornado import gen
from common import timetool
from appcommon.appinstance import mysql_app_pool
import settings


@gen.coroutine
def get_ad_list(ad_type):
    if ad_type == 0:
        param = 'circle=1'
    elif ad_type == 1:
        param = 'one=1'
    elif ad_type == 2:
        param = 'two=1'
    elif ad_type == 3:
        param = 'three=1'
    elif ad_type == 4:
        param = 'four=1'
    elif ad_type == 5:
        param = 'vip=1'
    elif ad_type == 6:
        param = '`index`=1'
    elif ad_type == 7:
        param = 'couch_index=1'
    elif ad_type == 8:
        param = 'student_index=1'
    elif ad_type == 9:
        param = 'couch_circle=1'
    else:
        param = 'pub_consult=1'
    sql = (
        "select id as ad_id, title_url, type as to_type, url from app_ad_info where {}"
    )
    res = yield mysql_app_pool.get_all(sql.format(
        param
    ), cursor='dict')
    raise gen.Return(res)


@gen.coroutine
def update_ad_view_cnt(ad_id):
    try:
        sql = "select 1 from app_view_cnt where view_id = {} and type=2"
        info = yield mysql_app_pool.get_one(sql.format(ad_id), cursor='dict')
        if info:
            sql_update = "update app_view_cnt set cnt=cnt+1 where view_id={} and type=2"
            yield mysql_app_pool.update(sql_update.format(ad_id))
        else:
            sql_insert = "insert into app_view_cnt (view_id,cnt,type) values ({}, 1, 2)"
            yield mysql_app_pool.update(sql_insert.format(ad_id))
        res = True
    except Exception, e:
        print e
        res = False
    raise gen.Return(res)


@gen.coroutine
def get_ad_content(ad_id):
    sql = (
        "select a.id as ad_id, a.title_url, a.title, a.pubtime, a.content as content,b.cnt as view_cnt "
        "from app_ad_info a,app_view_cnt b where a.id = {} and a.id=b.view_id and b.type=2"
    )
    info = yield mysql_app_pool.get_all(sql.format(ad_id), cursor='dict')
    raise gen.Return(info)

